package com.homevip.controller.platform;

import com.homevip.core.controller.BaseController;
import com.homevip.core.util.FastDate;
import com.homevip.user.entity.User;
import com.homevip.user.service.UserService;
import com.homevip.util.Base64Util;
import com.homevip.util.CookieUtil;
import com.homevip.util.UserSessionUtil;
import com.homevip.util.VerifyImage;
import com.homevip.util.gson.JsonUtil;
import com.homevip.util.http.HttpUtil;
import com.homevip.util.security.MD5MixUtil;
import com.homevip.util.system.Const;
import com.homevip.util.system.PlatformMenuUtil;
import com.homevip.web.annotation.DataTypeAnnotation;
import com.homevip.web.annotation.DataTypeEnum;
import com.homevip.web.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * 管理平台默认页面及菜单
 *
 * @author panpan
 */

@Controller
@RequestMapping("/platform/*")
public class PlatformController extends BaseController {

    @Autowired
    UserService userService;

    /**
     * 登陆页
     *
     * @throws Exception
     */
    @RequestMapping("/login")
    public void login(String ref, HttpServletRequest request) throws Exception {
        String auto_account = CookieUtil.getCookieValue(Base64Util.encode("account"), request);
        if (null != auto_account && auto_account.length() > 0) {
            request.setAttribute("autologin", 2);
        }
        if (null != ref) {
            ref = URLDecoder.decode(ref, Const.UTF8);
        }
        request.setAttribute("ref", ref);
        request.setAttribute("auto_account", auto_account);
    }

    /**
     * 登陆页
     *
     * @throws Exception
     */
    @RequestMapping("/ajax_login")
    @DataTypeAnnotation(DataTypeEnum.json)
    public void ajaxLogin(String account, Integer autologin, String password, String code, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ResultVo resultVo = new ResultVo();

        User user = userService.getUserByAccount(account);
        if (null != user) {
            if (
                    null != user
                            && user.getPassword().equals(MD5MixUtil.md5Mix(password))
                            && 2 == user.getStatus()
                            && null != code
                            && code.equals(UserSessionUtil.getRandCode(request))) {
                user.setLastlogin(new FastDate().toText());
                user.setLastip(HttpUtil.getIpAddr(request));
                user.setLogintimes(user.getLogintimes() + 1);//登陆次数+1
                userService.updateUser(user);
                UserSessionUtil.setUser(user, request);
                if (null != autologin && autologin == 2) {    //记住账号
                    CookieUtil.addCookie(Base64Util.encode("account"), user.getAccount(), response);
                } else {
                    CookieUtil.removeCookie(Base64Util.encode("account"), response);
                }
            } else {
                VerifyImage image = new VerifyImage();
                image.creatImage();
                UserSessionUtil.setRandCode(image.sRand, request);
                resultVo = new ResultVo(false, "登陆失败");
            }
        } else {
            resultVo = new ResultVo(false, "账号不存在");
        }
        writeJson(response, JsonUtil.toJson(resultVo));
    }

    /**
     * 菜单
     *
     * @throws Exception
     */
    @RequestMapping("/loadmenu")
    public void loadMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = UserSessionUtil.getUser(request);
        writeJson(response, PlatformMenuUtil.getSessionMenu(user, request).toString());
    }

    /**
     * 首页
     */
    @RequestMapping("/home")
    public void home(HttpServletRequest request) {
        User user = userService.getUserById(UserSessionUtil.getUser(request).getId());
        request.setAttribute("user", user);
    }

    /**
     * 验证码
     */
    @RequestMapping("verifyimage")
    public void verifyimage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        VerifyImage image = new VerifyImage();
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        ImageIO.write(image.creatImage(), "JPEG", response.getOutputStream());
        session.setAttribute(Const.SESSION_KEY_RAND, image.sRand);
    }

    /**
     * 登出
     *
     * @throws IOException
     */
    @RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {

        User user = UserSessionUtil.getUser(request);
        UserSessionUtil.removeUser(request);
        response.sendRedirect("login");
    }
}
